package cn.com.zero.job.core;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @author zhoupeng
 * @version 1.0.0
 * @Description zero job 数据库配置
 * @createTime 2022-07-15
 */
@Configuration
@MapperScan(basePackages = { "cn.com.zero.job.mapper" }, sqlSessionFactoryRef = "zeroJobSqlSessionFactory")
public class JobMybatisConfig {

    /**
     * 扫描 job-mapper 下的 xml
     */
    private static final String MAPPER_LOCATION = "classpath:/job-mapper/*Mapper.xml";

    /**
     * zero job 数据源单独管理
     */
    @ConfigurationProperties(prefix = "zero.job.datasource")
    @Bean("zeroJobDataSource")
    public DataSource dataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean("zeroJobSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        return factoryBean.getObject();
    }


}
